<?php
class Bliss_Media_Compressor_Javascript
{	
	protected $_method;
	protected $_contents;
	
	public function __construct($contents, $type='simple')
	{
		$this->_contents = $contents;
		$this->_method = "_compress".ucwords($type);
		if(!method_exists($this, $this->_method)) {
			throw new Bliss_Media_Exception("Javascript compressor type '{$type}' does not exist.");
		}
	}
	
	public function compress()
	{
		return call_user_func(array($this, $this->_method), $this->_contents);
	}
	
	protected function _compressClosure($contents)
	{
		$curl	= curl_init("http://closure-compiler.appspot.com/compile");
		$data	= array(
			'js_code'	=> $contents,
			'compilation_level'	=> 'SIMPLE_OPTIMIZATIONS',
			'output_info'	=> 'compiled_code',
			'output_format'	=> 'text'
		);
		
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_TIMEOUT, 100);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data, '', '&'));
		curl_setopt($curl, CURLOPT_HEADER, 0);
		
		$result	= curl_exec($curl);
		curl_close($curl);
		
		return $result;
	}

	protected function _compressSimple($contents)
	{
		$contents = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $contents);
    	$contents = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $contents);
		return $contents;
	}
	
}
?>